"""
Gunicorn 配置文件
"""

import os
import multiprocessing

# 服务器套接字
bind = f"0.0.0.0:{os.environ.get('PORT', 5000)}"
backlog = 2048

# Worker进程
workers = int(os.environ.get('GUNICORN_WORKERS', multiprocessing.cpu_count() * 2 + 1))
worker_class = "eventlet"  # 支持WebSocket
worker_connections = 1000
max_requests = 1000
max_requests_jitter = 50

# 超时设置
timeout = 300  # 5分钟，适合文档转换任务
keepalive = 2
graceful_timeout = 30

# 进程命名
proc_name = 'md2dockit'

# 用户和组
user = os.environ.get('GUNICORN_USER')
group = os.environ.get('GUNICORN_GROUP')

# 日志
accesslog = os.environ.get('GUNICORN_ACCESS_LOG', '-')
errorlog = os.environ.get('GUNICORN_ERROR_LOG', '-')
loglevel = os.environ.get('GUNICORN_LOG_LEVEL', 'info')
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s'

# 进程文件
pidfile = os.environ.get('GUNICORN_PID_FILE', '/tmp/gunicorn.pid')

# SSL配置（如果需要）
keyfile = os.environ.get('SSL_KEYFILE')
certfile = os.environ.get('SSL_CERTFILE')

# 预加载应用
preload_app = True

# 重启配置
reload = os.environ.get('GUNICORN_RELOAD', 'False').lower() == 'true'
reload_extra_files = []

# 安全配置
limit_request_line = 4094
limit_request_fields = 100
limit_request_field_size = 8190

# 性能调优
worker_tmp_dir = '/dev/shm'  # 使用内存文件系统提高性能

def when_ready(server):
    """服务器准备就绪时的回调"""
    server.log.info("MD2DocKit server is ready. Listening on: %s", server.address)

def worker_int(worker):
    """Worker进程接收到SIGINT信号时的回调"""
    worker.log.info("worker received INT or QUIT signal")

def pre_fork(server, worker):
    """Fork worker进程前的回调"""
    server.log.info("Worker spawned (pid: %s)", worker.pid)

def post_fork(server, worker):
    """Fork worker进程后的回调"""
    server.log.info("Worker spawned (pid: %s)", worker.pid)

def post_worker_init(worker):
    """Worker进程初始化后的回调"""
    worker.log.info("Worker initialized (pid: %s)", worker.pid)

def worker_abort(worker):
    """Worker进程异常退出时的回调"""
    worker.log.info("Worker aborted (pid: %s)", worker.pid)